"use client";

import { MainContext } from "@/src/providers/MainProvider";
import { MacroAction } from "@/src/types/types";
import {
  Button,
  Flex,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  NumberInput,
  NumberInputField,
  AlertDialog,
  AlertDialogBody,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogContent,
  AlertDialogOverlay,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import { useContext, useState, useRef } from "react";

function MacroActionList({
  list,
  onChange,
  startRecord,
}: {
  list: MacroAction[];
  onChange: Function;
  startRecord?: boolean;
}) {
  const [selected, setSelected] = useState(-1);
  const { isOpen, onOpen, onClose } = useDisclosure();
  const cancelRef = useRef<HTMLButtonElement>(null);

  const delAction = () => {
    if (startRecord) return; // 录制期间禁止删除
    if (list.length == 0) {
      return;
    }
    list.splice(selected, 1);
    onChange([...list]);
    setSelected(-1);
  };

  const moveUp = () => {
    if (startRecord) return; // 录制期间禁止移动
    if (list.length == 0) {
      return;
    }
    if (selected != 0) {
      const downAction = list[selected - 1];
      const upAction = list[selected];
      const headAction = list.slice(0, selected - 1);
      const tailAction = list.slice(selected + 1);

      onChange([...headAction, upAction, downAction, ...tailAction]);
      setSelected(selected - 1);
    }
  };
  const moveDown = () => {
    if (startRecord) return; // 录制期间禁止移动
    if (list.length == 0) {
      return;
    }
    if (selected != list.length - 1) {
      const downAction = list[selected];
      const upAction = list[selected + 1];
      const headAction = list.slice(0, selected);
      const tailAction = list.slice(selected + 2);
      onChange([...headAction, upAction, downAction, ...tailAction]);
      setSelected(selected + 1);
    }
  };
  const moveTop = () => {
    if (startRecord) return; // 录制期间禁止移动
    if (list.length == 0) {
      return;
    }
    if (selected != 0) {
      const selectAction = list.splice(selected, 1)[0];
      onChange([selectAction, ...list]);
      setSelected(0);
    }
  };
  const moveBottom = () => {
    if (startRecord) return; // 录制期间禁止移动
    if (list.length == 0) {
      return;
    }
    if (selected != list.length - 1) {
      const selectAction = list.splice(selected, 1)[0];
      onChange([...list, selectAction]);
      setSelected(list.length);
    }
  };

  const changeDelay = (value: number, select: number) => {
    if (startRecord) return; // 录制期间禁止修改延迟
    if (list.length == 0) {
      return;
    }
    const newList = list.map((action, index) =>
      index == select ? { ...action, delay: value } : action
    );
    onChange(newList);
  };

  const clearAllActions = () => {
    if (startRecord) return; // 录制期间禁止清空
    if (list.length > 0) {
      onOpen();
    }
  };

  const confirmClearAllActions = () => {
    onChange([]);
    setSelected(-1);
    onClose();
  };

  const { t } = useContext(MainContext);

    // 透明背景样式
    const transparentBgStyle = {
      backgroundColor: "rgba(255, 255, 255, 0.8)",
      backdropFilter: "blur(20px)",
      WebkitBackdropFilter: "blur(20px)",
      border: "1px solid rgba(255, 165, 0, 0.2)",
      borderRadius: "12px",
      boxShadow: "0 4px 20px rgba(255, 165, 0, 0.08)"
    };

  return (
    <div 
      className="p-0 macro-action-list flex flex-col h-[535px]"
    >
      <AlertDialog
        isOpen={isOpen}
        leastDestructiveRef={cancelRef}
        onClose={onClose}
        isCentered
      >
        <AlertDialogOverlay bg="rgba(0, 0, 0, 0.4)" backdropFilter="blur(8px)">
          <AlertDialogContent
            bg="rgba(255, 255, 255, 0.35)"
            backdropFilter="blur(10px)"
            borderRadius="12px"
            boxShadow="0 8px 32px rgba(0, 0, 0, 0.15)"
            border="1px solid rgba(255, 255, 255, 0.3)"
            p={4}
            maxW="md"
            mx="auto"
          >
            <AlertDialogHeader 
              fontSize="lg" 
              fontWeight="bold" 
              color="rgba(0, 0, 0, 0.8)"
              pb={2}
              textAlign="center"
            >
              {t("556")}
            </AlertDialogHeader>

            <AlertDialogBody
              color="rgba(0, 0, 0, 0.7)"
              fontSize="md"
              pb={6}
              textAlign="center"
            >
              {t("557")}
            </AlertDialogBody>

            <AlertDialogFooter 
              justifyContent="center" 
              gap={3}
            >
              <Button 
                ref={cancelRef} 
                onClick={onClose}
                variant="outline"
                borderColor="gray.300"
                _hover={{ bg: "rgba(0, 0, 0, 0.05)" }}
                minW="80px"
              >
                {t("559")}
              </Button>
              <Button 
                colorScheme="red" 
                onClick={confirmClearAllActions}
                boxShadow="0 2px 6px rgba(255, 0, 0, 0.2)"
                _hover={{ bg: "red.500" }}
                minW="80px"
              >
                {t("558")}
              </Button>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialogOverlay>
      </AlertDialog>

      <div className="flex-1">
        <ul 
          className="h-[475px] panel-main-fg overflow-y-auto pr-2" 
          style={transparentBgStyle}
        >
          <li className="py-1">
            <div>{t("531")}</div>
            <div>{t("532")}</div>
            <div>{t("533")}</div>
            <div>{t("534")}</div>
          </li>
          {list.map((action, index) => (
            <li
              className=""
              key={index}
              onClick={() => {
                if (startRecord) return; // 录制期间禁止选择
                setSelected(index);
              }}
              data-selected={index == selected}
              onContextMenu={() => {}}
              style={{
                pointerEvents: startRecord ? 'none' : 'auto',
                opacity: startRecord ? 0.6 : 1,
                cursor: startRecord ? 'not-allowed' : 'pointer'
              }}
            >
              <div className="text-sm text-center">{action.name}</div>
              <div>
                {action.action == 1 && t("525") }
                {action.action == 0 && t("526") }
                {action.action == 3 && t("537") }
                {action.action == 4 && t("536") }
                {action.action == 5 && t("540") }
                {action.action == 6 && t("541") }
              </div>
              <div>
                <NumberInput
                  className="!border-none"
                  value={action.delay}
                  min={1}
                  max={65535}
                  isDisabled={startRecord}
                  onClick={(event) => {
                    if (startRecord) return;
                    const t = event.target as HTMLInputElement;
                    t.select();
                  }}
                  onBlur={(evt) => {
                    if (startRecord) return;
                    // 确保值在有效范围内
                    const value = parseInt(evt.target.value);
                    if (isNaN(value) || value < 1) {
                      changeDelay(1, index);
                    } else if (value > 65535) {
                      changeDelay(65535, index);
                    }
                  }}
                  onChange={(s, n) => {
                    if (startRecord) return;
                    // 确保输入的值在有效范围内
                    if (n < 1) n = 1;
                    if (n > 65535) n = 65535;
                    changeDelay(n, index);
                  }}
                >
                  <NumberInputField
                    border={"none"}
                    padding={0}
                    textAlign={"right"}
                  />
                </NumberInput>
              </div>
              <div className="h-5">
                <Menu>
                  <MenuButton disabled={startRecord}>
                    <svg
                      className="h-5"
                      viewBox="0 0 1024 1024"
                      version="1.1"
                      xmlns="http://www.w3.org/2000/svg"
                      p-id="25981"
                      width="32"
                      height="32"
                      style={{
                        opacity: startRecord ? 0.6 : 1,
                        pointerEvents: startRecord ? 'none' : 'auto'
                      }}
                    >
                      <path
                        d="M512 128c-46.933333 0-85.333333 38.4-85.333333 85.333333s38.4 85.333333 85.333333 85.333334 85.333333-38.4 85.333333-85.333334-38.4-85.333333-85.333333-85.333333z m0 597.333333c-46.933333 0-85.333333 38.4-85.333333 85.333334s38.4 85.333333 85.333333 85.333333 85.333333-38.4 85.333333-85.333333-38.4-85.333333-85.333333-85.333334z m0-298.666666c-46.933333 0-85.333333 38.4-85.333333 85.333333s38.4 85.333333 85.333333 85.333333 85.333333-38.4 85.333333-85.333333-38.4-85.333333-85.333333-85.333333z"
                        p-id="25982"
                        fill="#e6e6e6"
                      ></path>
                    </svg>
                  </MenuButton>
                  <MenuList
                    p={0}
                    color={"gray"}
                    overflow={"hidden"}
                    fontSize={".85rem"}
                    minW={"3.5rem"}
                    textAlign={"center"}
                    borderRadius={"2px"}
                  >
                    <MenuItem onClick={() => moveTop()}>{t("535")}</MenuItem>
                    <MenuItem onClick={() => moveUp()}>{t("536")}</MenuItem>
                    <MenuItem onClick={() => moveDown()}>{t("537")}</MenuItem>
                    <MenuItem onClick={() => moveBottom()}>{t("538")}</MenuItem>
                  </MenuList>
                </Menu>
              </div>
            </li>
          ))}
        </ul>
      </div>

      <Flex
        justifyContent="flex-end"
        w="100%"
        gap={"1rem"}
        className="py-3 pr-2 h-[60px]"
      >
        <Button
          className="main-btn !px-6 !text-white"
          w="100px"
          colorScheme="red"
          variant="outline"
          onClick={clearAllActions}
          isDisabled={list.length === 0 || startRecord}
          opacity={startRecord ? 0.6 : 1}
          cursor={startRecord ? "not-allowed" : "pointer"}
          _hover={{ 
            bg: startRecord ? "transparent" : "rgba(255, 0, 0, 0.1)" 
          }}
        >
          {t("555")}
        </Button>
        
        <Button
          className="main-btn !px-6 w-20 !text-white"
          w="100px"
          onClick={() => delAction()}
          isDisabled={startRecord}
          opacity={startRecord ? 0.6 : 1}
          cursor={startRecord ? "not-allowed" : "pointer"}
          _hover={{
            bg: startRecord ? "transparent" : undefined
          }}
        >
          {t("505")}
        </Button>
      </Flex>
    </div>
  );
}

export default MacroActionList;
